package top.gangster.lunan.userservice.interceptor;

import com.auth0.jwt.JWT;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import top.gangster.lunan.userservice.annotation.PermissionLimit;
import top.gangster.lunan.userservice.entity.Role;
import top.gangster.lunan.userservice.entity.User;
import top.gangster.lunan.userservice.mapper.RoleMapper;
import top.gangster.lunan.userservice.mapper.UserMapper;
import top.gangster.lunan.userservice.service.UserService;

public class AuthInterceptor implements HandlerInterceptor {
  @Autowired
  private UserService userService;
  @Resource
  RoleMapper roleMapper;
  /**
   * 前置拦截器，用于权限验证
   * @param httpServletRequest 参数HttpServletRequest
   * @param httpServletResponse 参数HttpServletResponse
   * @param object 参数Object
   * @return t/f
   * @throws Exception 调用权限验证函数
   */
  @Override
  public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object)
      throws Exception {
    return permissionLimit(httpServletRequest, object);
  }

  private boolean permissionLimit(HttpServletRequest request, Object handler) throws Exception {
    // 如果不是方法
    if (!(handler instanceof HandlerMethod)){
      return true;
    }
    // 获取注解
    PermissionLimit pl = ((HandlerMethod)handler).getMethodAnnotation(PermissionLimit.class);
    // 如果没有注解就跳过
    if(pl == null){
      return true;
    }
    // 获取用户令牌
    String token = request.getHeader("Token");
    String roleId = JWT.decode(token).getAudience().get(3);
    System.out.println("权限验证roleid：");
    System.out.println(roleId);
    Role roleX = roleMapper.selectById(roleId);
    String authId = roleX.getAuthId();
    int authUser = Integer.parseInt(authId);
    int authReq = Integer.parseInt(pl.role());
      if (authUser<authReq){
        throw new RuntimeException("用户权限不足！");
      }

    return true;
  }
  @Override
  public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

  }
  @Override
  public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

  }
}
